import React, {	Component} from 'react';
import { connect } from 'dva'; //调取接口用
import { Table, Button, Card, Modal, Form, Icon, Input, Menu, Dropdown, message, TreeSelect, Select, Switch, Row, Col,DatePicker } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import moment from 'moment';
import styles from '../Mana/Role.less';
//课表

//select
const Option = Select.Option;

var room_select = [];//教室
var course_select=[];//课程
var class_select=[];//班级
let children = [];
for (let i = 10; i < 36; i++) {
  children.push(<Option key={i.toString(36) + i}>{i.toString(36) + i}</Option>);
}

//类型点击事件
function handleChange(value) {
	console.log(`selected ${value}`);
}
//时间戳 转化为时间格式
var Y,M,D,h,m,s="";
function timestampToTime(timestamp){
    var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000   //* 1000
    Y = date.getFullYear() + '/';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '/';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';  m = date.getMinutes() + ':';  s = date.getSeconds();
    return Y+M+D+h+m+s;
}
//table 列表
const columns = [
	{
	title: '序号',
		dataIndex: 'sequence',
		key: 'sequence',
	},
	{
	title: '班级名称',
		dataIndex: 'className',
		key: 'className',
	},{
		title: '教室名称',
		dataIndex: 'classroomName',
		key: 'classroomName',
	},{
		title: '课程名称',
		dataIndex: 'courseName',
		key: 'courseName',
	},{
		title: '人员名称',
		dataIndex: 'employeeName',
		key: 'employeeName',
	},{
		title: '补课老师',
		dataIndex: 'makeUpTeacherName',
		key: 'makeUpTeacherName',
	},{
		title: '教室状态',
		dataIndex: 'teacherStastus',
		key: 'teacherStastus',
		render: (text, record, index) =>{
			if(record.state==1){
				return "有效"
			}else if(record.state==0){
				return "无效"
			}
		} 
	},
];

var rowSelections = "";
//table复选框选中
// rowSelection objects indicates the need for row selection
const rowSelection = {
	onChange: (selectedRowKeys, selectedRows) => {
		console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
	},
	onSelect: (record, selected, selectedRows) => {
		rowSelections = new Object(); //声明对象
		rowSelections.selected = selected;
		rowSelections.selectedRows = selectedRows;
		console.log(record, selected, selectedRows);
	},
	onSelectAll: (selected, selectedRows, changeRows) => {
		rowSelections = new Object(); //声明对象
		rowSelections.selected = selected;
		rowSelections.selectedRows = selectedRows;
		console.log(selected, selectedRows, changeRows);
	},
};
//form 表单
const FormItem = Form.Item;
//表单内容
const CollectionCreateForm = Form.create()(
	(props) => {
		const {	visible,title,onCancel,onCreate,form,showModal,dispatch,objs} = props;
		const {getFieldDecorator} = form;
		return(
			<Modal
	        visible={visible}
	        title={title}
	        okText="确定"
	        onCancel={onCancel}
	        onOk={onCreate}
	      >
	        <Form layout="horizontal">
	          <FormItem label="班级" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('classId', {
	            	initialValue:objs.classId,
	              	rules: [{ required: true, message: '班级不能为空!' }],
	            })(
	              <Select showSearch placeholder="请选择" >
									{class_select}
								</Select>
	            )}
          	</FormItem>
            <FormItem label="教室" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('classroomId', {
	            	initialValue:objs.classroomId,
	              	rules: [{ required: true, message: '教室不能为空!' }],
	            })(
		            <Select showSearch placeholder="请选择"  >
									{room_select}
								</Select>
	            )}
          	</FormItem>
          	 <FormItem label="课程" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('courseId', {
	            	initialValue:objs.courseId,
	              	rules: [{ required: true, message: '课程不能为空!' }],
	            })(
		            <Select showSearch placeholder="请选择">
									{course_select}
								</Select>
	            )}
          	</FormItem>
          	<FormItem label="人员" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('employeeId', {
	            	initialValue:objs.employeeId,
	              	rules: [{ required: true, message: '人员不能为空!' }],
	            })(
		            <Select showSearch placeholder="请选择">
						{children}
					</Select>
	            )}
          	</FormItem>
          	<FormItem label="补课老师" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('makeUpTeacherName', {
	            	initialValue:objs.makeUpTeacherName,
	              	rules: [{ required: true, message: '补课老师不能为空!' }],
	            })(
		            <Select showSearch placeholder="请选择">
						{children}
					</Select>
	            )}
          	</FormItem>
          	<FormItem label="上课时间" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('ymdDate', {
	            	initialValue:objs.ymdDate,
	              	rules: [{ required: true, message: '上课时间不能为空!' }],
	            })(
		           <DatePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
	            )}
          	</FormItem>
          	<FormItem label="教室状态" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('teacherStastus', {
	            	initialValue:objs.teacherStastus,
	            })(
	              <Select showSearch    style={{ width: '100%' }} placeholder="请选择">
				    <Option value="1">有效</Option>
				    <Option value="0">无效</Option>
				  </Select>
	            )}
          	</FormItem>
        </Form>
      </Modal>
		);
	}
);

@connect(({ campus, loading }) => ({
  campus,
  loading: loading.models.campus,
}))
@Form.create()
class App extends React.Component {
	state = {
		confirmLoading: false,
		visible: false,
		title: "新增",
		objs: "", //编辑时赋值
	};
	//打开弹窗
	showModal = (title) => {
		this.form.resetFields();
		if(title == "新增") {
			this.setState({
				visible: true,
				title: title,
				objs: "",
			});
		}else{ //编辑
			if(!rowSelections || rowSelections.selected == false) {
				message.warning('还未选择数据,无操作');
			}else{
				if(rowSelections.selectedRows.length > 1) {
					message.warning('只能选择一项进行操作');
				} else {
					rowSelections.selectedRows[0].syllabusDateId+=''
					rowSelections.selectedRows[0].dateStatus+=''
					rowSelections.selectedRows[0].isDefault+=''
					this.setState({
						visible: true,
						title: title,
						objs: rowSelections.selectedRows[0],
					});
				}
			}
		}
	}
	//点击取消
	handleCancel = () => {
		this.setState({visible: false});
	}
	
	
	//新增  编辑
	handleCreate = (title) => {
		const form = this.form;
		form.validateFields((err, values) => {
			if(err) {	return;}
			console.log('Received values of form: ', values);
			
			values.ymdDate=timestampToTime(values.ymdDate);//上课时间  年月日
			values.week=moment(values.ymdDate).format("w");//周
		  values.ymdWeekDate=moment(values.ymdDate).format("YYYY")+moment(values.ymdDate).format("MM")+moment(values.ymdDate).format("w");//年月周
			if(values.teacherStastus==undefined){
				values.teacherStastus=1
			}
			console.log();
			form.resetFields();
			if(title == "新增") { //新增
				/*this.props.dispatch({
					type: 'campus/add_syllabus',
					payload: {...values},
					callback: (res,resMsg) => {
						if(res == 1) message.success(resMsg);
						else message.error(resMsg);
					},
				});*/
			} else { //编辑
				var Id = [];
				if(rowSelections.selectedRows.length == 1) {
					Id.push(rowSelections.selectedRows[0].syllabusDateId);
				} else {
					for(var i = 0; i < rowSelections.selectedRows.length; i++) {
						Id.push(rowSelections.selectedRows[i].syllabusDateId);
					}
				}
				this.props.dispatch({
					type: 'campus/edit_course_time',
					payload: {	...values,syllabusDateId: Id,},
					callback: (res, resMsg) => {
						if(res == 1)	message.success(resMsg); 
						else 	message.error(resMsg);
					},
				});
			}
			this.setState({
				visible: false,
			});
		});
	}
	/*删除*/
	deleaitModel = (title) => {
		const {	dispatch,	form} = this.props;
		console.log(rowSelections)
		if(!rowSelections || rowSelections.selected == false) {
			message.warning('还未选择数据,无操作');
		} else {
			var Id = [];
			if(rowSelections.selectedRows.length == 1) {
				Id.push(rowSelections.selectedRows[0].syllabusDateId);
			} else {
				for(var i = 0; i < rowSelections.selectedRows.length; i++) {
					Id.push(rowSelections.selectedRows[i].syllabusDateId);
				}
			}
			if(title == "dele") { //删除
				Modal.confirm({
					title: '是否删除选中项?',
					content: '删除后不可还原',
					okText: '确定',
					okType: 'danger',
					cancelText: '取消',
					onOk() { //调取批量删除组织机构
						dispatch({
							type: 'campus/remove_classroom',
							payload: {syllabusDateIds:Id},
							callback: (res,resMsg) => {
								if(res==1)	message.success(resMsg);
								else message.error(resMsg);
					        },
						});
					}
				});
			}else{
				var titles="";
				var state;
				if(title=="state1"){//启用
					titles="启用";
					state=1;
				}else{//禁用
					titles="禁用";
					state=0;
				}
				Modal.confirm({
					title: '是否'+titles+'选中项状态?',
					okText: '确定',
					cancelText: '取消',
					onOk() { //调取批量修改机构状态
						dispatch({
							type: 'campus/edit_course_time_state',
							payload: {syllabusDateIds: Id,state:state,},
							callback: (res, resMsg) => {
								if(res == 1) 	message.success(resMsg);
								else	message.error(resMsg);
							},
						});
					}
				});
			}
		}
	}
	//默认查询数据
	componentDidMount() {
		//默认查询table 数据
		this.props.dispatch({type: 'campus/fetch_syllabus'});
		//查询班级
		this.props.dispatch({
			type: 'campus/fetch_classselect',
			callback: (res,data) => {
				for (let i = 0; i < data.length; i++) {
				  class_select.push(<Option key={data[i].classId}>{data[i].name}</Option>);
				}
			}
		});
		//查询教室
		this.props.dispatch({
			type: 'campus/fetch_ListByroomselect',
			callback: (res,data) => {
				for (let i = 0; i < data.length; i++) {
				  room_select.push(<Option key={data[i].classroomId}>{data[i].name}</Option>);
				}
			}
		});
		//查询课程
		this.props.dispatch({
			type: 'campus/fetch_ListBycourseselect',
			callback: (res,data) => {
				for (let i = 0; i < data.length; i++) {
				  course_select.push(<Option key={data[i].id}>{data[i].value}</Option>);
				}
			}
		});
		//查询 教师
		this.props.dispatch({
			type: 'campus/fetch_EmployeeListByOrg',
			callback: (res,data) => {
				console.log(data)
				/*for (let i = 0; i < data.length; i++) {
				  course_select.push(<Option key={data[i].id}>{data[i].value}</Option>);
				}*/
			}
		});
		
		//查询补课老师
		
		
		
		
	}
	//重置
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'campus/fetch_syllabus',});
	}
	//查询
	handleSearch = (e) => {
		e.preventDefault();
		const {	dispatch,form} = this.props;
		form.validateFields((err, fieldsValue) => {
			if(err) return;
			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
			};
			this.setState({	formValues: values});
			if(values.classroomId==undefined){values.classroomId=""}
			if(values.courseId==undefined){values.courseId=""}
			if(values.employeeId==undefined){values.employeeId=""}
			if(values.upCourseDate==undefined){values.upCourseDate=""}
			dispatch({
				type: 'campus/fetch_syllabus',
				payload:{...values} 
			});
		});
	}
	saveFormRef = (form) => {this.form = form;}
	renderAdvancedForm() {
		const {getFieldDecorator} = this.props.form;
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		           <Col md={8} sm={24}>
		            <FormItem label="班级">
		              {getFieldDecorator('classId')(
		               <Select showSearch  style={{ width: '100%' }} placeholder="请选择">
							{children}
						</Select>
		              )}
		            </FormItem>
		          </Col>
		          <Col md={8} sm={24}>
		            <FormItem label="结束时间">
		              {getFieldDecorator('endDate')(
		               <DatePicker showTime format="YYYY-MM-DD HH:mm:ss"/>
		              )}
		            </FormItem>
		          </Col>
		           <Col md={8} sm={24}>
		            <FormItem label="时间状态">
		              {getFieldDecorator('dateStatus')(
		                <Select showSearch    style={{ width: '100%' }} placeholder="请选择">
						    <Option value="1">有效</Option>
						    <Option value="0">无效</Option>
						</Select>
		              )}
		            </FormItem>
		          </Col>
		        </Row>
		        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
		          <Col md={8} sm={24}>
		            <FormItem label="备注">
		              {getFieldDecorator('remark')(
		                 <Input />
		              )}
		            </FormItem>
		          </Col>
		           <Col md={16} sm={24}>
		            <FormItem>
			            <span style={{ float: 'right', marginBottom: 24 }}>
			            <Button type="primary" htmlType="submit">查询</Button>
			            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
			            </span>
		            </FormItem>
		          </Col>
		        </Row>
		    </Form>
		);
	}
	render() {
		const {	visible,title,confirmLoading} = this.state;
		const { campus: { data=[] }, loading } = this.props;
		const rowKey = function(data) {return data.syllabusId;/*主键id*/};
		return(
			<PageHeaderLayout title="">
        		<Card bordered={false}>
        		<div className={styles.tableList}>
		            <div className={styles.tableListForm}>
		              {this.renderAdvancedForm()}
		            </div>
					<div className={styles.table_operations} >
				      	<Button icon="plus" type="primary"  onClick={() => this.showModal('新增')}>新增</Button>
				      	<Button icon="edit" type="primary"  onClick={() => this.showModal('编辑')}>编辑</Button>
				      	<Button icon="minus" type="primary" onClick={() => this.deleaitModel('dele')}>删除</Button>
				      	<Button icon="edit" type="primary"  onClick={() => this.deleaitModel('state1')}>启用</Button>
					    <Button icon="edit" type="ghost"  onClick={() => this.deleaitModel('state0')}>禁用</Button>
				    </div>
				    <CollectionCreateForm  alt="弹窗" 
				          ref={this.saveFormRef}
				          title={this.state.title}
				          objs={this.state.objs}
				          confirmLoading={confirmLoading}
				          visible={this.state.visible}
				          onCancel={this.handleCancel} 
				          onCreate={() => this.handleCreate(this.state.title)}
				    />
				    <Table rowKey={rowKey} columns={columns} rowSelection={rowSelection} loading={loading}  dataSource={data}  pagination={{ pageSize: 10 }}/>
				</div>
	      		</Card>
	   		</PageHeaderLayout>
		)
	}
}
export default() => (<App />)